package weiyao.xinxidasai.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import weiyao.xinxidasai.DTO.Result;
import weiyao.xinxidasai.Utils.ThreadLocal.UserHolder;
import weiyao.xinxidasai.pojo.FFiles;
import weiyao.xinxidasai.service.DownloadService;

import java.io.IOException;
import java.util.Collections;

@RestController
@RequestMapping("/download")
@CrossOrigin
public class DownloadController {
    private static final int PRESIGNED_URL_EXPIRATION = 3600 * 1000; // 1小时有效

    private final DownloadService downloadService;

    @Autowired
    public DownloadController(DownloadService downloadService) {
        this.downloadService = downloadService;
    }

    /**
     * 普通文件下载
     * @param fileId 文件ID
     * @return 文件响应实体
     */
    @GetMapping("/file/{fileId}")
    public ResponseEntity<?> downloadFile(@PathVariable Long fileId) {
        try {
            return downloadService.downloadFile(fileId);
        } catch (IOException e) {
            return ResponseEntity.internalServerError()
                    .body(Result.fail("文件下载失败: " + e.getMessage()));
        } catch (RuntimeException e) {
            return ResponseEntity.status(403)
                    .body(Result.fail(e.getMessage()));
        }
    }

    /**
     * 分片下载初始化
     * @param fileId 文件ID
     * @return 文件信息和分片信息
     */
    @GetMapping("/chunk/init/{fileId}")
    public Result initChunkDownload(@PathVariable Long fileId) {
        try {
            FFiles fileInfo = downloadService.initChunkDownload(fileId);
            return Result.ok("分片下载初始化成功", fileInfo);
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 下载单个分片
     * @param fileId 文件ID
     * @param index 分片索引
     * @param chunkSize 分片大小
     * @return 分片数据响应实体
     */
    @GetMapping("/chunk/{fileId}")
    public ResponseEntity<?> downloadChunk(
            @PathVariable Long fileId,
            @RequestParam Integer index,
            @RequestParam Long chunkSize) {

        try {
            return downloadService.downloadChunk(fileId, index, chunkSize);
        } catch (IOException e) {
            return ResponseEntity.internalServerError()
                    .body(Result.fail("分片下载失败: " + e.getMessage()));
        } catch (RuntimeException e) {
            return ResponseEntity.status(403)
                    .body(Result.fail(e.getMessage()));
        }
    }



    /**
     * 获取文件信息（用于下载前展示）
     * @param fileId 文件ID
     * @return 文件基本信息
     */
    @GetMapping("/info/{fileId}")
    public Result getFileInfo(@PathVariable Long fileId) {
        try {
            FFiles fileInfo = downloadService.initChunkDownload(fileId);
            return Result.ok("文件信息获取成功", fileInfo);
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }
}